package httpDemo

import (
	"fmt"
	"html/template"
	"io/ioutil"
	"log"
	"net/http"
	"session"
	"strings"
	"time"
	"util"
)

var sessionManager *session.SessionManager

func init() {

}

func StartDemo() {
	for {
		time.Sleep(2 * time.Second)
		resp, err := http.Get("http://127.0.0.1:9999/")
		defer resp.Body.Close()
		util.CheckError(err)
		fmt.Println("StatusCode:", resp.StatusCode)
		for key, val := range resp.Header {
			fmt.Printf("%v:%v\n", key, val)
		}
		input, err := ioutil.ReadAll(resp.Body)
		util.CheckError(err)
		fmt.Println(string(input))

	}
	//httpClient()
	//simpleServer()
	//templateDemo()
	//sessionDemo()
}

func sessionDemo() {
	//启动Session管理器
	var err error
	//不能使用:=，:=会创建局部变量
	sessionManager, err = session.NewManager("memory", "sessionId", 300)
	if err != nil {
		fmt.Println(err)
	}
	go sessionManager.GC()

	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		session := sessionManager.SessionStart(w, r)
		name := session.Get("username")
		if name != nil {
			fmt.Fprintln(w, "<html><body><a href='/login'>登录</a>", name, "</body></html>")
		} else {
			fmt.Fprintln(w, "<html><body><a href='/login'>登录</a></body></html>")
		}
	})
	http.HandleFunc("/login", func(w http.ResponseWriter, r *http.Request) {
		// printHeader(r)
		// printRequest(r)
		// fmt.Println("method:", r.Method)
		if r.Method == "GET" {
			t, _ := template.ParseFiles("login.gtpl")
			t.Execute(w, nil)
		}
		if r.Method == "POST" {
			r.ParseForm()
			fmt.Println("username:", r.Form["username"])
			if len(strings.Join(r.Form["username"], "")) == 0 {
				fmt.Println("empty username")
			}
			//设置session
			session := sessionManager.SessionStart(w, r)
			session.Set("username", string([]byte(strings.Join(r.Form["username"], ""))))
			//输出到客户端
			// fmt.Fprint(w, strings.Join(r.Form["username"], ""))
			//html转义输出到客户端
			template.HTMLEscape(w, []byte(strings.Join(r.Form["username"], "")))
		}
	})
	startListent()
}

func templateDemo() {
	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		fmt.Fprintln(w, "<html><body><a href='/login'>登录</a></body></html>")
	})
	http.HandleFunc("/login", func(w http.ResponseWriter, r *http.Request) {
		printHeader(r)
		printRequest(r)
		fmt.Println("method:", r.Method)
		if r.Method == "GET" {
			t, _ := template.ParseFiles("login.gtpl")
			t.Execute(w, nil)
		}
		if r.Method == "POST" {
			r.ParseForm()
			fmt.Println("username:", r.Form["username"])
			if len(strings.Join(r.Form["username"], "")) == 0 {
				fmt.Println("empty username")
			}
			//设置cookie
			cookie := http.Cookie{Name: "username", Value: string([]byte(strings.Join(r.Form["username"], "")))}
			http.SetCookie(w, &cookie)
			//输出到客户端
			// fmt.Fprint(w, strings.Join(r.Form["username"], ""))
			//html转义输出到客户端
			template.HTMLEscape(w, []byte(strings.Join(r.Form["username"], "")))
		}
	})
	startListent()
}

func simpleServer() {
	//监听地址及回调
	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		r.ParseForm() //解析参数，默认不解析参数
		fmt.Println(r.Form)
		fmt.Println("Path:" + r.URL.Path)
		fmt.Println("Scheme:" + r.URL.Scheme)
		for k, v := range r.Form {
			fmt.Println("key:" + k)
			fmt.Println("value:" + strings.Join(v, ""))
		}
		fmt.Fprintln(w, "OK!")
	})
	startListent()
}

func startListent() {
	fmt.Println("start...9999")
	//监听端口
	err := http.ListenAndServe(":9999", nil)
	if err != nil {
		fmt.Printf("error:%v\n", err)
		log.Fatal(err)
	}
}

//打印请求header
func printHeader(r *http.Request) {
	fmt.Println("-----------------Header Start----------------")
	for key, valArr := range r.Header {
		fmt.Printf("%v:%v\n", key, strings.Join(valArr, " "))
	}
	fmt.Println("-----------------Header End------------------")
}

//打印请求参数
func printRequest(r *http.Request) {
	fmt.Println("-----------------Request Start----------------")
	r.ParseForm()
	for k, v := range r.Form {
		fmt.Printf("%v:%v\n", k, strings.Join(v, " "))
	}
	fmt.Println("-----------------Request End------------------")
}
func httpClient() {
	resp, err := http.Get("http://www.baidu.com")
	defer resp.Body.Close()
	util.CheckError(err)
	fmt.Println("StatusCode:", resp.StatusCode)
	for key, val := range resp.Header {
		fmt.Printf("%v:%v\n", key, val)
	}
	input, err := ioutil.ReadAll(resp.Body)
	util.CheckError(err)
	fmt.Println(string(input))
}
